import 'package:flutter/material.dart';
import 'package:safety_platform/models/risk_unit.dart';
// import 'package:safety_platform/models/risk_unit_page.dart';
import 'package:safety_platform/components/loading.dart';
import 'package:flutter_refresh/flutter_refresh.dart';
// import 'package:eas';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/bezier_circle_header.dart';

import 'package:safety_platform/pages/services.dart';
import 'package:safety_platform/pages/risk_unit/detail.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:safety_platform/bloc/risk/risk.dart';

class RiskUnitListPage extends StatefulWidget {
  State<StatefulWidget> createState() => _RiskUnitListPageState();
}

class _RiskUnitListPageState extends State<RiskUnitListPage> {
  RiskUnitListBloc _bloc;
  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      bloc: _bloc,
      child: Scaffold(
        appBar: AppBar(
          title: new Text('风险单元'),
          elevation: 0,
          backgroundColor: Color.fromARGB(255, 27, 130, 210),
          centerTitle: true, //设置标题是否局中
        ),
        // bottomNavigationBar: _buildBottomNavigationBar(task),
        body: BlocBuilder(
          bloc: _bloc,
          builder: (BuildContext context, RiskUnitListState stat) =>
              _body(stat),
        ),
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    _bloc = RiskUnitListBloc();
    _bloc.dispatch(RiskUnitRefreshEvent());
  }

  @override
  void dispose() {
    super.dispose();
    _bloc.dispose();
  }

  void _onRefresh() {
    _bloc.dispatch(RiskUnitRefreshEvent());
  }

  Widget _body(RiskUnitListState state) {
    if (state is RiskUnitListState) {
      return RiskUnitListWidget(
          state.data, () => _bloc.dispatch(RiskUnitRefreshEvent()));
    }
  }
}

class RiskUnitListWidget extends StatefulWidget {
  final List<RiskUnit> data;
  final Function onRefresh;
  RiskUnitListWidget(this.data, this.onRefresh);
  State<StatefulWidget> createState() => _RiskUnitListWidgetState();
}

class _RiskUnitListWidgetState extends State<RiskUnitListWidget> {
  // RiskUnitPage page;

  // List<RiskUnit> data;
  GlobalKey<RefreshHeaderState>
      _headerKey; //= new GlobalKey<RefreshHeaderState>();
  GlobalKey<RefreshFooterState> _footerKey;
  GlobalKey<EasyRefreshState> _easyRefreshKey =
      new GlobalKey<EasyRefreshState>();
  @override
  void initState() {
    super.initState();
    // fetchAllRiskUnit().then((List<RiskUnit> data) {
    //   setState(() {
    //     this.data = data;
    //   });
    // });
    _headerKey = GlobalKey();
    _footerKey = GlobalKey();
  }

  @override
  Widget build(BuildContext context) {
    return _body(context);
  }

  void didUpdateWidget(RiskUnitListWidget oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget != widget) {
      if (_easyRefreshKey.currentState != null) {
        if (_easyRefreshKey.currentState.isRefreshing) {
          _easyRefreshKey.currentState.callRefreshFinish();
        }
        _easyRefreshKey.currentState.callLoadMoreFinish();
      }
      // _headerKey.currentState.c
      // _headerKey.currentState.
      // if (_controller.isRefresh(true)) {
      // _controller.sendBack(true, RefreshStatus.completed);
    }
  }

  Widget _item(BuildContext context, int index) {
    // RiskUnit unit = page.results[index];
    // List<String> code = ['A', 'B', 'C', 'D', 'E', 'F'];
    // List<String> codeName = ['生产单元', '辅助生产单元', '仓储单元', '动力单元', '管理单元', '生活单元'];
    RiskUnit riskUnit = widget.data[index];
    String asset = 'assets/risk_unit_${riskUnit.category.prefix}.png';
    String name = riskUnit.unitName;
    return Card(
      color: Colors.white,
      margin: EdgeInsets.fromLTRB(8, 4, 8, 4),
      elevation: 0,
      child: InkWell(
        onTap: () {
          Navigator.of(context).push(
              MaterialPageRoute(builder: (_) => RiskUnitDetailPage(riskUnit:riskUnit)));
        },
        child: Container(
          // color: Colors.red,
          child: Column(children: <Widget>[
            Row(
              children: <Widget>[
                Container(
                  decoration: BoxDecoration(
                    border: Border(
                        // right: BorderSide(
                        //   width: 0.5,
                        //   // color: Theme.of(context).primaryColor,
                        //   color: Color.fromARGB(255, 241, 241, 241),
                        // ),
                        ),
                  ),
                  padding: EdgeInsets.fromLTRB(16, 8, 16, 8),
                  width: 100,
                  child: Column(
                    children: <Widget>[
                      Image.asset(
                        asset,
                        width: 32,
                        height: 32,
                      ),
                      // Text(
                      //   '5',
                      //   style: TextStyle(fontSize: 22),
                      // ),
                      Padding(
                        padding: EdgeInsets.symmetric(vertical: 4),
                        child: Text(
                          '${riskUnit.riskCount} 风险点',
                          /* */
                          style: TextStyle(
                            color: Colors.grey,
                            fontSize: 13,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                Expanded(
                    child: Container(
                  height: 64,
                  padding: EdgeInsets.fromLTRB(8, 8, 8, 8),
                  // color: Theme.of(context).primaryColor,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Text(name,
                          // maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.w500,
                          )),
                      Row(children: <Widget>[
                        Expanded(
                          flex: 2,
                          child: Text(
                            '编号：${riskUnit.unitCode}',
                            style: TextStyle(color: Colors.grey
                                // color: Colors.white,
                                ),
                          ),
                        ),
                        // Expanded(
                        //   flex: 1,
                        //   child: Container(
                        //     padding: EdgeInsets.symmetric(vertical: 4),
                        //     decoration: BoxDecoration(
                        //       color: Colors.grey,
                        //       borderRadius: BorderRadius.circular(4.0)
                        //     ),
                        //     child:Text(
                        //     '',

                        //     textAlign: TextAlign.center,
                        //     style: TextStyle(
                        //       fontSize: 13,
                        //       color: Colors.white),
                        //   )),
                        // )
                      ]),
                    ],
                  ),
                )),
              ],
            ),
            // _riskItem()
          ]),
        ),
      ),
    );
  }

  Future<Null> _onRefresh() {
    widget.onRefresh();
    return Future.value(null);
  }

  Future<Null> _loadMore() {
    // if (widget.loadMore != null) {
    // widget.loadMore();
    // } else {
    // _easyRefreshKey.currentState.callLoadMoreFinish();
    // }
    return Future.value(null);
  }

  _body(BuildContext context) {
    // print('data $data');
    if (widget.data == null) {
      return Center(
        child: Loading(),
      );
    } else {
      if (widget.data.length > 0) {
        return EasyRefresh(
            refreshHeader: BezierCircleHeader(
              key: _headerKey,
              color: Colors.white70,
              backgroundColor: Theme.of(context).primaryColor,
              // textColor: Colors.black54,
              // refreshText: '下拉刷新',
              // refreshReadyText: '释放即开始刷新',
              // refreshingText: '刷新中，请稍候..',
              // refreshedText: '刷新完成',
            ),
            refreshFooter: ClassicsFooter(
              key: _footerKey,
              loadText: '上拉加载更多',
              noMoreText: '没有更多数据了',
              loadReadyText: '释放加载更多',
              loadingText: '正在加载，请稍候..',
              loadedText: '加载完成',
              bgColor: Colors.white70,
              // bgColor: Theme.of(context).backgroundColor,
              textColor: Colors.black54,
            ),
            key: _easyRefreshKey,
            autoControl: false,
            onRefresh: _onRefresh,
            loadMore: _loadMore,
            // enablePullDown: true,
            // enablePullUp: true,
            // onRefresh: _onRefresh,
            // controller: _controller,
            // footerConfig: LoadConfig(
            // bottomWhenBuild: false,
            // ),
            // headerBuilder: (BuildContext context, int mode) {
            //   return ClassicIndicator(
            //     mode: mode,
            //     refreshingText: '正在刷新',
            //     completeText: '刷新成功',
            //     idleText: '下拉刷新',
            //     releaseText: '下拉刷新',
            //   );
            // },
            // onOffsetChange: _onOffsetCallback,÷
            child: new ListView.builder(
              itemCount: widget.data.length,
              itemBuilder: (context, index) => _item(context, index),
            ));
        // return Refresh(
        //   child: ListView.builder(
        //     itemCount: data.length,
        //     itemBuilder: (context, index) => _item(context, index),
        //     // itemCount: page == null? 0: page.results.length,
        //   ),
        // );
      }
    }
    return Container();
  }
}
